// 用户行为跟踪和对话记忆服务
import { ref } from 'vue';

// 用户行为类型定义
export interface UserBehavior {
  type: 'query' | 'click' | 'view' | 'search';
  content: string;
  timestamp: number;
  category?: string; // 健康主题分类
  tags?: string[];   // 相关标签
}

// 对话历史类型
export interface Conversation {
  id: string;
  messages: {
    from: 'user' | 'model';
    content: string;
    timestamp: number;
  }[];
  summary?: string; // 对话摘要
  tags?: string[];  // 对话标签
}

// 用户偏好类型
export interface UserPreferences {
  interests: {[key: string]: number}; // 兴趣主题及权重
  preferredLanguage: string;
  responseType: 'detailed' | 'concise';
  healthConcerns?: string[]; // 健康关注点
}

class UserBehaviorService {
  private behaviors = ref<UserBehavior[]>([]);
  private conversations = ref<Conversation[]>([]);
  private preferences = ref<UserPreferences>({
    interests: {},
    preferredLanguage: 'zh-CN',
    responseType: 'detailed'
  });
  private currentConversationId = ref<string>('');

  constructor() {
    this.loadFromLocalStorage();
  }

  // 记录用户行为
  recordBehavior(behavior: UserBehavior): void {
    this.behaviors.value.push(behavior);
    this.updatePreferences(behavior);
    this.saveToLocalStorage();
  }

  // 开始新对话
  startNewConversation(): string {
    const id = Date.now().toString();
    this.currentConversationId.value = id;
    this.conversations.value.push({
      id,
      messages: []
    });
    return id;
  }

  // 添加消息到当前对话
  addMessageToConversation(from: 'user' | 'model', content: string): void {
    if (!this.currentConversationId.value) {
      this.startNewConversation();
    }

    const conversation = this.conversations.value.find(c => c.id === this.currentConversationId.value);
    if (conversation) {
      conversation.messages.push({
        from,
        content,
        timestamp: Date.now()
      });

      // 生成对话摘要（当消息数量超过3条时）
      if (conversation.messages.length >= 3 && !conversation.summary) {
        this.generateConversationSummary(conversation);
      }

      this.saveToLocalStorage();
    }
  }

  // 生成对话摘要
  private generateConversationSummary(conversation: Conversation): void {
    // 简单的摘要生成逻辑，实际应用中可以使用AI模型
    const userMessages = conversation.messages
      .filter(m => m.from === 'user')
      .map(m => m.content);
    
    if (userMessages.length > 0) {
      // 提取关键词作为标签
      const commonHealthTerms = [
        '感冒', '发烧', '头痛', '咳嗽', '高血压', '糖尿病', 
        '心脏病', '过敏', '失眠', '焦虑', '抑郁', '肥胖',
        '运动', '饮食', '营养', '维生素', '药物', '治疗'
      ];

      const tags = commonHealthTerms.filter(term => 
        userMessages.some(msg => msg.includes(term))
      );

      conversation.tags = tags.slice(0, 3); // 最多3个标签
      conversation.summary = userMessages[0].length > 50 
        ? userMessages[0].substring(0, 50) + '...' 
        : userMessages[0];
    }
  }

  // 更新用户偏好
  private updatePreferences(behavior: UserBehavior): void {
    // 提取健康主题关键词
    const healthCategories = {
      '症状咨询': ['症状', '不舒服', '难受', '疼痛', '异常'],
      '用药指导': ['药物', '药', '服用', '剂量', '副作用'],
      '疾病预防': ['预防', '避免', '降低', '减少', '防止'],
      '健康生活': ['健康', '生活', '饮食', '运动', '习惯'],
      '医疗机构': ['医院', '诊所', '医生', '预约', '检查']
    };

    // 识别行为所属分类
    for (const [category, keywords] of Object.entries(healthCategories)) {
      if (keywords.some(keyword => behavior.content.includes(keyword))) {
        behavior.category = category;
        // 更新兴趣权重
        this.preferences.value.interests[category] = 
          (this.preferences.value.interests[category] || 0) + 1;
        break;
      }
    }

    // 更新健康关注点
    const healthConcerns = [
      '心血管', '呼吸', '消化', '神经', '内分泌', '免疫',
      '骨骼', '皮肤', '五官', '精神'
    ];

    healthConcerns.forEach(concern => {
      if (behavior.content.includes(concern) && 
          !this.preferences.value.healthConcerns?.includes(concern)) {
        if (!this.preferences.value.healthConcerns) {
          this.preferences.value.healthConcerns = [];
        }
        this.preferences.value.healthConcerns.push(concern);
      }
    });
  }

  // 获取用户偏好
  getUserPreferences(): UserPreferences {
    return this.preferences.value;
  }

  // 获取推荐内容
  getRecommendations(count: number = 3): string[] {
    // 根据用户兴趣生成推荐
    const interests = this.preferences.value.interests;
    const sortedCategories = Object.entries(interests)
      .sort(([,a], [,b]) => b - a)
      .map(([category]) => category);

    const recommendations: string[] = [];
    
    // 基于分类生成推荐
    if (sortedCategories.includes('症状咨询')) {
      recommendations.push('您可能想了解常见症状的自我护理方法');
    }
    if (sortedCategories.includes('用药指导')) {
      recommendations.push('查看常用药物的正确使用指南');
    }
    if (sortedCategories.includes('疾病预防')) {
      recommendations.push('了解季节性疾病的预防措施');
    }
    if (sortedCategories.includes('健康生活')) {
      recommendations.push('获取个性化的健康生活方式建议');
    }
    if (sortedCategories.includes('医疗机构')) {
      recommendations.push('查找附近的医疗机构和专科医生');
    }

    // 添加通用推荐
    const generalRecommendations = [
      '了解如何保持良好的心理健康',
      '探索适合您的运动计划',
      '获取均衡饮食的实用建议',
      '了解定期体检的重要性'
    ];

    while (recommendations.length < count) {
      const randomRec = generalRecommendations[Math.floor(Math.random() * generalRecommendations.length)];
      if (!recommendations.includes(randomRec)) {
        recommendations.push(randomRec);
      }
    }

    return recommendations.slice(0, count);
  }

  // 获取对话历史
  getConversationHistory(): Conversation[] {
    return this.conversations.value.slice().reverse();
  }

  // 设置当前对话
  setCurrentConversation(conversationId: string): void {
    const conversation = this.conversations.value.find(c => c.id === conversationId);
    if (conversation) {
      this.currentConversationId.value = conversationId;
    }
  }

  // 清除所有数据
  clearAllData(): void {
    this.behaviors.value = [];
    this.conversations.value = [];
    this.preferences.value = {
      interests: {},
      preferredLanguage: 'zh-CN',
      responseType: 'detailed'
    };
    this.currentConversationId.value = '';
    localStorage.removeItem('userBehaviors');
    localStorage.removeItem('conversations');
    localStorage.removeItem('userPreferences');
  }

  // 保存到本地存储
  private saveToLocalStorage(): void {
    localStorage.setItem('userBehaviors', JSON.stringify(this.behaviors.value));
    localStorage.setItem('conversations', JSON.stringify(this.conversations.value));
    localStorage.setItem('userPreferences', JSON.stringify(this.preferences.value));
  }

  // 从本地存储加载
  private loadFromLocalStorage(): void {
    const behaviors = localStorage.getItem('userBehaviors');
    const conversations = localStorage.getItem('conversations');
    const preferences = localStorage.getItem('userPreferences');

    if (behaviors) {
      this.behaviors.value = JSON.parse(behaviors);
    }
    if (conversations) {
      this.conversations.value = JSON.parse(conversations);
    }
    if (preferences) {
      this.preferences.value = JSON.parse(preferences);
    }
  }
}

// 导出单例实例
export const userBehaviorService = new UserBehaviorService();